package damon.utils;

import damon.common.ConstantObject;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class OpcUtil {
    /*
     * 	与西门子opc建立通讯的2次握手协议
     */
    static public boolean handshake(InputStream is, OutputStream os) throws IOException, DecoderException {
        //第一次握手
        byte[] onecBytes = onceSocketCommunication(is, os, Hex.decodeHex(ConstantObject.HANDSHAKE_PROTOCOL_SEND_ONCE));
//        String onecReply = new String(Hex.encodeHex(onecBytes)).toUpperCase();

        //第二次握手
        byte[] twiceBytes = onceSocketCommunication(is, os, Hex.decodeHex(ConstantObject.HANDSHAKE_PROTOCOL_SEND_TWICE));
//        String twiceReply = new String(Hex.encodeHex(twiceBytes)).toUpperCase();
        return true;
    }


    /*
     * 	向socket服务端发送一次报文，并等待该次报文的回复。
     */
    static public byte[] onceSocketCommunication(InputStream is, OutputStream os, byte[] sendBytes) throws IOException {
        os.write(sendBytes);
        byte[] bytes = new byte[ConstantObject.REPLY_BYTE_SIZE];

        int len = is.read(bytes);
        if (len == -1) {
            throw new RuntimeException("socket read length -1");
        }
        byte[] cutZeroBytes = new byte[len];// 存放去除多余零后的字节数组
        //无法确定socket服务端发送的具体报文大小，字节数组必须尽可能的大。因此字节数组末尾会产生多余的0。
        // 字节数组去零
        System.arraycopy(bytes, 0, cutZeroBytes, 0, len);
        return cutZeroBytes;
    }
}
